package com.example.springmvc.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author fanhang
 */
@Configuration
public class JwtCodec {
    private final String issuer;
    private final Algorithm algorithm;

    public JwtCodec(@Value("#{jwt.secret}") String secret, @Value("#{jwt.issuer}") String issuer) {
        this.issuer = issuer;
        this.algorithm = Algorithm.HMAC256(secret);
    }

    public String encode() {
        return JWT.create().withIssuer(issuer).sign(algorithm);
    }

    public Long decode(String token) {
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
        DecodedJWT decodedJwt = verifier.verify(token);
        return Long.valueOf(decodedJwt.getId());
    }
}
